import route from 'koa-route';
import Game from '../game/Game';
import { SocketRequest } from '../interface/index'
import { broadCast, Globel } from '../lib/tools';
import fs from 'fs';
import path from 'path';
export const playerSocket = route.all('/games/:roomid', async (ctx, params) => {
    let room_id = params as string;
    let room = Globel.rooms.get(room_id);
    if(!room){
        ctx.websocket.close();
        return;
    }
    let userid: string | null = null;
    ctx.websocket.on('message', async(res) => {
        let data: SocketRequest = JSON.parse(res.toString());
        switch (data.cmd) {
            case 'go':
                room!.game.playergo(data.userid, data.data.cards!);
                break;
            case 'playerToScore':
                room!.game.playerToScore(data.userid, data.data.score);
                break;
            case 'ready':
                room!.game.playerReady(data.userid, data.data.isReady);
                break;
            case 'join':
                let str = await fs.readFileSync(path.resolve(__dirname,"../static/userdata.json")).toString();
                let userdata = JSON.parse(str);
                userid = data.userid;
                if(!userdata[userid]){
                    ctx.websocket.close(1000,"玩家未注册");
                    return;
                }
                //是否有相同的玩家
                let hasPlayer = false;
                room!.playerClients.forEach(v=>{
                    if(v.userid==userid) hasPlayer = true; 
                })
                if(hasPlayer){
                    ctx.websocket.close(1000,"存在相同玩家");
                    return;
                }
                if (room!.playerClients.size >= 3) {
                    ctx.websocket.close(1000,"房间已满");
                    return;
                }
                console.log(userid);
                room!.playerClients.set(userid,{
                    userid: userid!,
                    ctx: ctx
                });
                let indexArr:number[] = [];
                room!.game.playerMap.forEach(v=>indexArr.push(v.index));
                let userIndex = 0;
                if(!indexArr.includes(2)) userIndex = 2;
                if(!indexArr.includes(1)) userIndex = 1;
                if(!indexArr.includes(0)||!indexArr.length) userIndex = 0;
                room!.game.playerMap.set(userid,{
                    username:userdata[userid].username,
                    userid: userid,
                    scoreNum:userdata[userid].scoreNum,
                    icon:userdata[userid].icon,
                    score: -1,
                    sex:userdata[userid].sex,
                    index:userIndex,
                    ready: false
                })
                let playerList:string[] = [];
                room!.playerClients.forEach(v=>{playerList.push(v.userid)});
                broadCast({
                    cmd: 'join',
                    userid: userid,
                    players: playerList,
                }, room!.playerClients)
                break;
        }
    })

    ctx.websocket.on('close', (code,reason) => {
        console.log(code,reason);
        room!.playerClients.delete(userid!);
        room!.game.playerMap.delete(userid!);
        room!.usercount--;
        console.log(room!.game.playerMap.size);
        if (room!.playerClients.size==0) {
            Globel.rooms.delete(room_id);
            return;
        }
        broadCast({
            cmd: 'ext',
            userid: userid!
        }, room!.playerClients)
        
        if (room!.playerClients.size == 2) room!.game.reset();

    })

})

